<?php
namespace app\index\controller;

use app\index\controller\Base;
use think\Db;
use think\facade\Log;
use think\facade\Request;

use \WeChatPay\Builder;
use \WeChatPay\Crypto\Rsa;
use \WeChatPay\Util\PemUtil;
use \WeChatPay\Formatter;
use WeChatPay\Crypto\AesGcm;


class Notify extends Base
{
    public function _empty()
    {
        //重定向浏览器
        header("Location:/404.html");
        //确保重定向后，后续代码不会被执行
        exit;
    }
	
	
	public function wxpay(){
		$testxml  = file_get_contents("php://input");
		$result = json_decode($testxml, true);//转成数组，
		$info = Request::header();
		Log::write($result, 'lizhili78912result');
		Log::write($info, 'lizhili78912info');
		if (!isset($info['wechatpay-signature'])) {
		    //重定向浏览器
		    header("Location:/404.html");
		    //确保重定向后，后续代码不会被执行
		    exit;
		}
		$inWechatpaySignature = $info['wechatpay-signature'];// 请根据实际情况获取
		$inWechatpayTimestamp = $info['wechatpay-timestamp'];// 请根据实际情况获取
		$inWechatpaySerial = $info['wechatpay-serial'];// 请根据实际情况获取
		$inWechatpayNonce = $info['wechatpay-nonce'];// 请根据实际情况获取
		
		$inBody = $testxml;// 请根据实际情况获取，例如: file_get_contents('php://input');
        $config=Db::name('mall_config')->column('value','key');
		$apiv3Key = $config['wx_v3_secret'];// 在商户平台上设置的APIv3密钥
		$platformPublicKeyInstance = Rsa::from(file_get_contents(env('root_path').'zhengshu/wechatpay.pem'), Rsa::KEY_TYPE_PUBLIC);
		// 检查通知时间偏移量，允许50分钟之内的偏移
		$timeOffsetStatus = 3000 >= abs(Formatter::timestamp() - (int)$inWechatpayTimestamp);
		$verifiedStatus = Rsa::verify(
		    // 构造验签名串
		    Formatter::joinedByLineFeed($inWechatpayTimestamp, $inWechatpayNonce, $inBody),
		    $inWechatpaySignature,
		    $platformPublicKeyInstance
		);
		Log::write($timeOffsetStatus, 'lizhili78912');
		Log::write($verifiedStatus, 'lizhili78912');
		if ($timeOffsetStatus && $verifiedStatus) {
		    // 转换通知的JSON文本消息为PHP Array数组
		    $inBodyArray = (array)json_decode($inBody, true);
		    // 使用PHP7的数据解构语法，从Array中解构并赋值变量
		    ['resource' => [
		        'ciphertext'      => $ciphertext,
		        'nonce'           => $nonce,
		        'associated_data' => $aad
		    ]] = $inBodyArray;
		    // 加密文本消息解密
		    $inBodyResource = AesGcm::decrypt($ciphertext, $apiv3Key, $nonce, $aad);
		    // 把解密后的文本转换为PHP Array数组
		    $inBodyResourceArray = (array)json_decode($inBodyResource, true);
			Log::write($inBodyResourceArray, 'lizhili7891');
		    // print_r($inBodyResourceArray);// 打印解密后的结果
			$result=$inBodyResourceArray;
			if ($result['trade_state'] == 'SUCCESS') {
			    $out_trade_no = 'zong_'.$result['out_trade_no'];
				if($gu=Db::name('order')->where('out_trade_no', $out_trade_no)->where('pay_status', 0)->find()){
					Db::name('order')->where('id',$gu['id'])->update([
					    'pay_status'=>1,
					    'order_time'=>time(),
					    'pay_price'=>$result['amount']['payer_total']/100,
						'wx_order_tui'=>$result['transaction_id']
					]);
					$this->fen($out_trade_no);
					//减少库存
					if($goods=Db::name('goods')->where('id',$gu['goods_id'])->find()){
						Db::name('goods')->where('id',$goods['id'])->setDec('kucun_num', $gu['order_num']);
					}
					return \json([
					      "code"=> "SUCCESS",
					        "message"=> "成功"
					   ]);
				}
			}
		}
		die;
	}
	//分钱
	protected function fen($out_trade_no=false){
		Log::write($out_trade_no, 'lizhili7891out_trade_no');
		if($out_trade_no){
			$mall_config_order=Db::name('mall_config_order')->column('value','key');
			$order=Db::name('order')->where('out_trade_no', $out_trade_no)->find();
			$user=Db::name('user')->where('id',$order['user_id'])->find();
			$goods=Db::name('goods')->where('id',$order['goods_id'])->find();
			if($goods and $goods['fen_money']){
				$true_money=$goods['fen_money']*$order['order_num'];
				if($goods['lei']==1){ //普通商城分润
					$f_user=Db::name('user')->where('id',$user['fid'])->find();
					if($f_user){
						Db::name('user')->where('id',$f_user['id'])->update([
							'money'=>$f_user['money']+$true_money,
							'money_zong'=>$f_user['money_zong']+$true_money,
						]);
						//记录
						Db::name('money')->insert([
							'uid'=>$f_user['id'],
							'money'=>$true_money,
							'type'=>3,
							'time'=>time(),
							'order_id'=>$out_trade_no
						]);
					}
				}
				if($goods['lei']==4){ //团购分润
					if($mall_config_order['zong_fen'] and $mall_config_order['zong_bank']){
						// $money=$order['pay_price']*$mall_config_order['zong_fen']/100; 修改了支付的钱
						$money=$true_money*$mall_config_order['zong_fen']/100;
						Log::write($money, 'lizhili7891money');
						//生成订单
						$orderid=time().mt_rand(10000,99999).$user['id'];
						$info=[
							'out_trade_no'=>$orderid,
							'order_id'=>$out_trade_no,
							'to_uid'=>$mall_config_order['zong_bank'],
							'bili'=>$mall_config_order['zong_fen'],
							'wx_order_tui'=>$order['wx_order_tui'],
							'money'=>$money,
							'time'=>time(),
						];
						Log::write($info, 'lizhili7891money');
						if(Db::name('order_fen')->insert($info)){
							Log::write(Db::getLastSql(), 'lizhili7891money');
							$config=Db::name('mall_config')->column('value','key');
							$merchantId = $config['wx_merchat_id'];
							// 从本地文件中加载「商户API私钥」，「商户API私钥」会用来生成请求的签名
							$merchantPrivateKeyFilePath = file_get_contents(env('root_path').'zhengshu/apiclient_key.pem');
							$merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);
							// 「商户API证书」的「证书序列号」
							$merchantCertificateSerial = $config['wx_zhengshu'];
							// 从本地文件中加载「微信支付平台证书」，用来验证微信支付应答的签名
							$platformCertificateFilePath = file_get_contents(env('root_path').'zhengshu/wechatpay.pem');
							$platformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);
							// 从「微信支付平台证书」中获取「证书序列号」
							$platformCertificateSerial = PemUtil::parseCertificateSerialNo($platformCertificateFilePath);
							// 构造一个 APIv3 客户端实例
							$instance = Builder::factory([
							    'mchid'      => $merchantId,
							    'serial'     => $merchantCertificateSerial,
							    'privateKey' => $merchantPrivateKeyInstance,
							    'certs'      => [
							        $platformCertificateSerial => $platformPublicKeyInstance,
							    ],
							]);
							Log::write((string)($money*100), 'lizhili7891moneystring');
							
							  try {
							      $resp = $instance
							      ->chain('v3/profitsharing/orders')
							      ->post(['json' => [
									  'appid'=>$config['wx_merchat_id'],
									  'transaction_id'=>$order['wx_order_tui'],
									  'out_order_no'=>$orderid,
									  'unfreeze_unsplit'=>true,
									  'receivers'=>[
											  'type'=>'MERCHANT_ID',
											  'account'=>$mall_config_order['zong_bank'],
											  'amount'=>(string)($money*100),
											  'description'=>'分账获取，订单id：'.$order['id']
									  ]
								  ]]);
							      if( $resp->getStatusCode()==200){
									$wo=json_decode($resp->getBody(),true); //prepay_id
									Log::write($wo, 'lizhili7891123');
								   if($wo['state']=='FINISHED'){
									   Db::name('order_fen')->where('out_trade_no',$orderid)->update([
									       'iswan'=>1,
										   'text'=>json_encode($wo)
									   ]);
								   }
								  // return ['code' => 1, 'message' => '微信支付成功','data'=>$params];
							   }
							  } catch (\Exception $e) {
							   // return ['code' => 0, 'message' => '微信支付错误'];
							      // 进行错误处理
							      echo $e->getMessage(), PHP_EOL;
								  Log::write($e->getMessage(), 'lizhili7891123cuo');
							      if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
							          $r = $e->getResponse();
							          echo $r->getStatusCode() . ' ' . $r->getReasonPhrase(), PHP_EOL;
									  Log::write($r->getStatusCode(), 'lizhili7891123cuo');
							          echo $r->getBody(), PHP_EOL, PHP_EOL, PHP_EOL;
									  Log::write($r->getBody(), 'lizhili7891123cuo');
							      }
							      echo $e->getTraceAsString(), PHP_EOL;
								  Log::write($e->getTraceAsString(), 'lizhili7891123cuo');
							  }
							
						}
					}
					$order=Db::name('order')->where('out_trade_no', $out_trade_no)->find();
					$tuan_uid=Db::name('tuan')->where('id',$order['tuan_id'])->value('uid');
					$qudao_uid=Db::name('user')->where('id',$tuan_uid)->value('fid');
					$qudao_user=Db::namr('user')->where('id',$qudao_uid)->find();
					
					if($tuan_uid){
						$fen1=Db::name('user')->where('id',$tuan_uid)->find();
						//$money=$order['pay_price']*$mall_config_order['fuye_fen']/100; 修改了支付的钱
						$money=$true_money*$mall_config_order['fuye_fen']/100;
						Db::name('user')->where('id',$fen1['id'])->update([
							'money'=>$fen1['money']+$money,
							'money_zong'=>$fen1['money_zong']+$money,
						]);
						//记录
						Db::name('money')->insert([
							'uid'=>$fen1['id'],
							'money'=>$money,
							'type'=>1,
							'time'=>time(),
							'order_id'=>$out_trade_no
						]);
					}
					if($qudao_uid and isset($qudao_user['shenfen']) and $qudao_user['shenfen']==1){
						$fen2=Db::name('user')->where('id',$qudao_uid)->find();
						// $money=$order['pay_price']*$mall_config_order['hehuo_fen']/100; 修改了支付的钱
						$money=$true_money*$mall_config_order['hehuo_fen']/100;
						Db::name('user')->where('id',$fen2['id'])->update([
							'money'=>$fen2['money']+$money,
							'money_zong'=>$fen2['money_zong']+$money,
						]);
						//记录
						Db::name('money')->insert([
							'uid'=>$fen2['id'],
							'money'=>$money,
							'type'=>1,
							'time'=>time(),
							'order_id'=>$out_trade_no
						]);
					}
				}
				
				
				
			}
			
			
		}
	}

    public function alipay() //这个是阿里 的回调
    {
        $data=input('post.');
        Log::write($data, 'debug');
        require_once "aop/AopCertClient.php";
		$alipayCertPath = env('root_path')."zhengshu/alipayCertPublicKey_RSA2.crt";
        $aop = new \AopCertClient;
		 $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
        $flag = $aop->rsaCheckV1($data, null, "RSA2");
        Log::write($flag, 'debug');
        if ($flag) {
            $order = Db::name('order')->where('out_trade_no', $data['out_trade_no'])->find();
            Log::write($order, 'debug');
            if ($order) {
                $fen=Db::name('order')->where('id', $order['id'])->where('pay_status', 0)->update([
                'pay_status'=>1,
                'pay_price'=>$data['buyer_pay_amount'],//支付的金额
                'order_time'=>time(),
                'notify_id'=>$data['notify_id'],
                'trade_no'=>$data['trade_no'],
              ]);
                echo 'success';
            } else {
                echo 'fail';
            }
        } else {
            echo 'fail';
        }
    }
}
